package com.juli.school.app.controller.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Map;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.juli.school.dao.entity.UploadRecord;
import com.juli.school.service.impl.UploadRecordService;
import com.juli.school.service.utils.ThumbnailUtils;
import com.juli.school.utils.core.model.CommonResp;

/**
 * @Description: 寻物/失物控制器
 * @author gaoxiang
 * @date 2017年8月24日 下午10:07:23
 */
@Controller
@RequestMapping("/file")
public class FileController {
	
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);
	
	@Resource
	UploadRecordService uploadRecordService;
	
	String path = "E:/file/%s/%s/%s/%s/";
	
	@RequestMapping("/gotoUpload")
	String gotoUpload() {
		return "fileUpload";
	}
	
	/**
	 * @Description: 校验文件是否已存在
	 * @author gaoxiang
	 * @date 2017年10月23日 下午6:33:52
	 */
	@RequestMapping("/checkFile")
	@ResponseBody
	CommonResp<String> checkFile(String digest) {
		return uploadRecordService.getByDigest(digest);
	}
	
	/**
	 * @Description: 图片上传
	 * @author gaoxiang
	 * @date 2017年9月17日 下午9:23:26
	 */
	@RequestMapping("/upload")
	@ResponseBody
	CommonResp<String> upload(String type, String category, String digest, MultipartFile pictureFile) {
		logger.info("文件上传开始,类型->{},模块->{}", type, category);
		CommonResp<String> commonResp = new CommonResp<String>();
		if (Strings.isNullOrEmpty(digest)) {
			commonResp.fail("文件摘要不可为空");
			return commonResp;
		}
		// 原始文件名
		String currentTimeMillis = String.valueOf(System.currentTimeMillis());
		String fileName = currentTimeMillis + "_" + pictureFile.getOriginalFilename();
		logger.info("file name: {}", fileName);
		long size = pictureFile.getSize() / (1024 * 1024);
		logger.info("file size: {} 兆", size);
		Calendar calendar = Calendar.getInstance();
		String targetPath = String.format(path, category, calendar.get(GregorianCalendar.YEAR), calendar.get(GregorianCalendar.MONTH) + 1,
				calendar.get(GregorianCalendar.DAY_OF_MONTH));
		File targetFile = new File(targetPath, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 缩略图文件名
		String digestFileName = currentTimeMillis + pictureFile.getOriginalFilename() + "_digest_.jpg";
		File digestFile = new File(targetPath, digestFileName);
		try {
			pictureFile.transferTo(targetFile);
			// 保存缩略图
			ThumbnailUtils.saveThumbnail(type, targetFile, digestFile);
		} catch (Exception e) {
			logger.error("保存文件异常", e);
			commonResp.fail("保存文件异常" + e.toString());
			return commonResp;
		}
		String picPath = targetPath + digestFileName;
		String fileUrl = targetPath + fileName;
		InputStream is = null;
		BufferedImage src = null;
		int width = -1;
		int height = -1;
		if ("0".equals(type)) {
			try {
				is = new FileInputStream(targetFile);
				src = ImageIO.read(is);
				// 得到源图宽
				width = src.getWidth();
				// 得到源图宽
				height = src.getHeight();
			} catch (Exception e) {
			} finally {
				IOUtils.closeQuietly(is);
			}
		}
		try {
			UploadRecord uploadRecord = new UploadRecord();
			uploadRecord.setDigest(digest);
			uploadRecord.setName(fileName);
			uploadRecord.setPicPath(picPath);
			uploadRecord.setSrcPath(fileUrl);
			uploadRecord.setType(type);
			uploadRecord.setWidth(width+"");
			uploadRecord.setHeight(height+"");
			uploadRecordService.addUploadRecord(uploadRecord);
		} catch (Exception e) {
			logger.error("保存上传记录异常", e);
			commonResp.fail("保存上传记录异常" + e.toString());
			return commonResp;
		}
		commonResp.success();
		Map<String, Object> data = Maps.newHashMap();
		data.put("picPath", picPath);
		data.put("srcPath", fileUrl);
		data.put("width", width);
		data.put("height", height);
		commonResp.setExtraData(data);
		logger.info("文件上传成功,模块->{}", category);
		return commonResp;
	}
	
	/**
	 * @Description: 图片下载
	 * @author gaoxiang
	 * @date 2017年9月17日 下午10:00:45
	 */
	@RequestMapping("/download")
	public void download(HttpServletResponse response, String path, String range) {
		response.setContentType("application/octet-stream;charset=UTF-8");
		if (Strings.isNullOrEmpty(path))
			return;
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.substring(path, path.lastIndexOf('/'), path.length()));
			FileInputStream in = new FileInputStream(path);
			byte[] data = new byte[in.available()];
			in.read(data);
			IOUtils.closeQuietly(in);
			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentLength(data.length);
			// response.setHeader("Content-Length", "" + data.length);
			// 如果客户端指定的range超过或等于文件大小，则返回416状态码
			if (!Strings.isNullOrEmpty(range) && Integer.valueOf(range) >= data.length) {
				response.setStatus(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE.value());
				return;
			}
			IOUtils.write(data, outputStream);
			outputStream.flush();
			IOUtils.closeQuietly(outputStream);
		} catch (Exception e) {
			logger.error("查找图片异常" + path, e);
		}
	}
}
